<?php

//SANITIZE ALL ESCAPES
$sanitize_all_escapes=true;

//STOP FAKE REGISTER GLOBALS
$fake_register_globals=false;

$ignoreAuth=true;

require_once("../interface/globals.php");
require_once("../library/sql-ccr.inc");
require_once("ccr/createCCR.php");

ini_set("soap.wsdl_cache_enabled", "0"); // disabling WSDL cache
$server = new SoapServer("http://bolivar.saludaunclic.com/wsdl/bolivar.wsdl");	// Locate WSDL file to learn structure of functions

$server->addFunction("get_schedule");	// Same func name as in our WSDL XML, and below
$server->addFunction("login");	// Same func name as in our WSDL XML, and below
$server->addFunction("create_CCR");	// Same func name as in our WSDL XML, and below
$server->addFunction("get_appointments");	// Same func name as in our WSDL XML, and below
$server->addFunction("schedule_appointment");	// Same func name as in our WSDL XML, and below
$server->addFunction("validate_patient");	// Same func name as in our WSDL XML, and below
$server->addFunction("find_available");	// Same func name as in our WSDL XML, and below
$server->handle();  

function get_schedule( $formdata ){
	
		$formdata = get_object_vars($formdata);
		$user = $formdata['User'];
		$startdate = $formdata['Startdate'];
		$enddate = $formdata['Enddate'];
		
		if($user!=''){
			$sxe = new SimpleXMLElement(file_get_contents("base_file.xml"));
		
			$query = " SELECT ope.*, u.username, pd.pubpid, pd.fname, pd.lname " .
			" FROM openemr_postcalendar_events ope INNER JOIN users u ON ( ope.pc_aid = u.id ) inner join patient_data pd on ( ope.pc_pid = pd.pid ) " .
			" WHERE (ope.pc_aid = '$user' OR u.username = '$user' ) " .
			" AND pc_eventDate >= '$startdate' " .
			" AND pc_eventDate <= '$enddate' " .
			" AND ( pc_catid = '1' OR pc_catid = '5' OR pc_catid = '9' OR pc_catid = '10' OR pc_catid = '14' OR pc_catid = '15' )";
			
			$result = sqlStatement($query);
			if( sqlNumRows($result) > 0 ){
				while( $row = sqlFetchArray($result)){
					$appointment = $sxe->addChild('appointment', '');
					$paciente = $appointment->addChild('Paciente', '');
					$paciente->addChild('numeroid', $row['pubpid']);
					$paciente->addChild('nombre', $row['fname']);
					$paciente->addChild('apellido', $row['lname']);
					$appointment->addChild('pc_catid', $row['pc_catid']);				
					$appointment->addChild('pc_title', $row['pc_title']);
					$appointment->addChild('pc_time', $row['pc_time']);				
					$appointment->addChild('pc_comments', $row['pc_comments']);
					$appointment->addChild('pc_counter', $row['pc_counter']);
					$appointment->addChild('pc_topic', $row['pc_topic']);				
					$appointment->addChild('fecha_cita', $row['pc_eventDate']);				
					$appointment->addChild('duracion_segundos', $row['pc_duration']);				
					$appointment->addChild('hora_inicio', $row['pc_startTime']);
					$appointment->addChild('hora_final', $row['pc_endTime']);
					$appointment->addChild('pc_eventstatus', $row['pc_eventstatus']);
					$appointment->addChild('pc_apptstatus', $row['pc_apptstatus']);
					$appointment->addChild('pc_facility', $row['pc_facility']);
				}
				//$sxe->encoding = 'iso-8859-1';
				return array('Success' => $sxe->asXML() );
			}
		}
		
}

function login($formdata){
	$formdata = get_object_vars($formdata); // Pull parameters from SOAP 	
	$new_pass = md5($formdata['Password']);
	$username = $formdata['Username'];
	if($username!=''){
		$query = 	" SELECT * " .
				" FROM users " .
				" WHERE username = '$username' ";
			
		$result = sqlStatement($query);
		if( sqlNumRows($result)> 0 ){
			$row = sqlFetchArray($result);
			if( $new_pass == $row['password'] ){
				$sxe = new SimpleXMLElement(file_get_contents("base_file.xml"));
				$medico = $sxe->addChild("User",'');
				$medico->addChild('Name',$row['fname']." ".$row['lname']);
				$medico->addChild('ID', $row['id']);
				$medico->addChild('Specialty', $row['speciality']);
				$medico->addChild('success',"1");
				$success = $sxe->asXML();
			}else{
				$sxe = new SimpleXMLElement(file_get_contents("base_file.xml"));
				$medico = $sxe->addChild("User",'');
				$medico->addChild('content',"Usuario o contraseña no coinciden.");
				$medico->addChild('success',"0");
				$success = $sxe->asXML();
			}
		}else{
			$sxe = new SimpleXMLElement(file_get_contents("base_file.xml"));
			$medico = $sxe->addChild("User",'');
			$medico->addChild('content',"Usuario no existe.");
			$medico->addChild('success',"-1");
			$success = $sxe->asXML();
		}

		return array('Success' => $success);
	}
	
}

function create_CCR($formdata){
    $formdata = get_object_vars($formdata);	
    $pubpid = $formdata['Patientid'];
	
	if($pubpid!=''){
		$query = "SELECT * from patient_data where pubpid='$pubpid'";    
		
		$result = sqlStatement($query);
		
		if(sqlNumRows($result) > 0){
			$row = sqlFetchArray($result);								   
			$pid = $row['pid'];			
			$return_value = createCCR('generate',$pid,'yes');
			
			return array('Success' => $return_value);         
		}
	}		
}

function get_appointments($formdata){
    $formdata = get_object_vars($formdata); // Pull parameters from SOAP 	
	$pid = $formdata['Patientid'];
	
	if($pid!=''){	
		/*$query = " SELECT * , users.fname mfname, users.lname mlname, f.name ffname ".
		" FROM openemr_postcalendar_events ope " .
			"INNER JOIN patient_data pd ON ( ope.pc_pid = pd.pid ) " .
			"INNER JOIN facility f on ( ope.pc_facility = f.id ) " .
			"INNER JOIN users u on ( ope.pc_aid = u.id ) " .
		" WHERE pd.pubpid = '$pid' AND ope.pc_eventDate >= NOW()";
		$query = "SELECT  e.* ," .
			" u.fname mfname, u.lname mlname, u.username, f.name " .
			" FROM openemr_postcalendar_events AS e, users AS u, facility AS f, " .
			" patient_data AS pd WHERE " .
			" pd.pubpid = '$pid' AND e.pc_eventDate >= CURRENT_DATE AND " .
			" u.id = e.pc_aid  AND pd.pid = e.pc_pid AND u.facility_id = f.id " .
			" ORDER BY e.pc_eventDate, e.pc_startTime ";*/
			

		$query = "  SELECT  e.* , u.fname mfname, u.lname mlname, u.username, f.name facility_name
					FROM openemr_postcalendar_events e
						INNER JOIN users u on ( e.pc_aid = u.id )
						INNER JOIN users_facility uf on (u.id = uf.table_id)
						INNER JOIN facility f on (f.id = uf.facility_id)
						INNER JOIN patient_data pd on (pd.pid = e.pc_pid)
					WHERE  pd.pubpid = '112160581' AND e.pc_eventDate >= CURRENT_DATE
					ORDER BY e.pc_eventDate, e.pc_startTime ";
			
		
		$result = sqlStatement($query);

		if( sqlNumRows($result) > 0 ){
			$sxe = new SimpleXMLElement(file_get_contents("base_file.xml"));
			
			while( $row = sqlFetchArray($result) ){
				$appointment = $sxe->addChild('appointment', '');
				
				$appointment->addChild('pc_aid', $row['pc_aid']);
				$medico = $appointment->addChild('medico', '');
				$medico->addChild( 'nombre', $row['mfname'] );
				$medico->addChild( 'apellido', $row['mlname'] );
				$appointment->addChild('fecha_inicio', $row['pc_eventDate']);
				$appointment->addChild('fecha_final', $row['pc_endDate']);
				$appointment->addChild('duracion_segundos', $row['pc_duration']);
				$appointment->addChild('hora_inicio', $row['pc_startTime']);
				$appointment->addChild('hora_final', $row['pc_endTime']);
				$appointment->addChild('establecimiento', $row['name']);
			}
			return array('Success' => $sxe->asXML() );
		}
	}
}

function schedule_appointment($formdata){
    $formdata = get_object_vars($formdata);
   
	$pid = $formdata['Patientid'];
	$message = $formdata['Message'];
	if($pid!=''){
		$query1 = " SELECT * FROM patient_data WHERE pubpid  = $pid ";
		$res1 = sqlStatement($query1);
		if( sqlNumRows($res1) > 0 ){
			$row1 = sqlFetchArray($res1);
			$mypid = $row1['pid'];
			
			$query = " SELECT * " .
						"FROM gacl_groups_aro_map ggam " .
							"INNER JOIN gacl_aro ga on ( ggam.aro_id = ga.id ) " .
							"INNER JOIN users u on ( ga.value = u.username ) " .
						"WHERE ggam.group_id = 29 ";
						
			$result = sqlStatement($query);	
			if( sqlNumRows($result) > 0 ){
				while( $row = sqlFetchArray($result) ){
					$user = $row['username'];
					$query2 = " INSERT INTO pnotes ( pid, body, date, assigned_to, title, user, groupname, activity, authorized, message_status ) VALUES " .
							" ( '$mypid', '$message', NOW(), '$user', '1', '$user', 'default', 1, 1, '1') ";
					$result2 = sqlStatement($query2);	
				}
				return array('Success' => "Mensajes enviados correctamente" );
			}
		}
	}
}

function validate_patient($formdata){
    $formdata = get_object_vars($formdata); // Pull parameters from SOAP 	
	$pid = $formdata['Patientpid'];
	$pname = $formdata['Patientname'];
	
	if($pid!=''){
		$query = " SELECT * " .
			" FROM patient_data " .
			" WHERE pubpid = '$pid' ";
	
		$result = sqlStatement($query);

		if( sqlNumRows($result) > 0 ){
			$row = sqlFetchArray($result);
			//die(print_r($row));
			if( $pname == $row['fname'] ){
				$success = 1;
			}else{
				$success = 0;
			}
		}else{
			$success = -1;
		}				
		return array('Success' => $success);
	}				
}

function doOneDay($catid, $udate, $starttime, $duration, $prefcatid) {
    global $slots,  $slotstime, $slotbase, $slotcount, $input_catid;
	$slotsecs = 30;
    $udate = strtotime($starttime, $udate);
    if ($udate < $slotstime) return;
    $i = (int) ($udate / $slotsecs) - $slotbase;
    $iend = (int) (($duration + $slotsecs - 1) / $slotsecs) + $i;
    if ($iend > $slotcount) $iend = $slotcount;
    if ($iend <= $i) $iend = $i + 1;
    for (; $i < $iend; ++$i) {
    if ($catid == 2) {        // in office
        // If a category ID was specified when this popup was invoked, then select
        // only IN events with a matching preferred category or with no preferred
        // category; other IN events are to be treated as OUT events.
        if ($input_catid) {
            if ($prefcatid == $input_catid || !$prefcatid)
                $slots[$i] |= 1;
             else
                $slots[$i] |= 2;
        } else {
            $slots[$i] |= 1;	
        }
        break; // ignore any positive duration for IN
    } else if ($catid == 3) { // out of office
        $slots[$i] |= 2;
        break; // ignore any positive duration for OUT
    } else { // all other events reserve time
        $slots[$i] |= 4;
    }
  }
  
  
}

function find_available($formdata){
    $formdata = get_object_vars($formdata); 

	if($formdata['Specialty']!=''&&$formdata['StartDate']){
		$input_catid = 9;
        $slotsecs = 1800;
        $catslots = 1;
		$eid = 0;
		$sxe = new SimpleXMLElement(file_get_contents("base_file.xml"));
        if ($input_catid) {
            $query = "SELECT pc_duration FROM openemr_postcalendar_categories WHERE pc_catid = '$input_catid'";
			$srow = sqlStatement($query);
			if( sqlNumRows($srow) > 0 ){
			$row = sqlFetchArray($srow);
            if ($row['pc_duration']) $catslots = ceil($row['pc_duration'] / $slotsecs);
			}
        }
        $info_msg = "";
        $searchdays = 7; // default to a 1-year lookahead
         // Get a start date.
        if ($formdata['StartDate'] && preg_match("/(\d\d\d\d)\D*(\d\d)\D*(\d\d)/",
            $formdata['StartDate'], $matches))
        {
         $sdate = $matches[1] . '-' . $matches[2] . '-' . $matches[3];
         $sdatenew = $matches[3] . '/' . $matches[2] . '/' . $matches[1];
        } else {
         $sdate = date("Y-m-d");
         $sdatenew = date("d/m/Y");
        }
		//return array('Success' => $sdate);
        // Get an end date - actually the date after the end date.
        preg_match("/(\d\d\d\d)\D*(\d\d)\D*(\d\d)/", $sdate, $matches);
        $edate = date("Y-m-d",
        mktime(0, 0, 0, $matches[2], $matches[3] + $searchdays, $matches[1]));
        // compute starting time slot number and number of slots.
        $slotstime = strtotime("$sdate 00:00:00");
        $slotetime = strtotime("$edate 00:00:00");
        $slotbase  = (int) ($slotstime / $slotsecs);
        $slotcount = (int) ($slotetime / $slotsecs) - $slotbase;
		
		
		
		
        //if ($slotcount <= 0 || $slotcount > 100000) //die("Invalid date range.".$slotcount);
        $slotsperday = (int) (60 * 60 * 24 / $slotsecs);
        $evslots = $catslots;
		
		
    
        $evslots = 60 * 30;
        $evslots = (int) (($evslots + $slotsecs - 1) / $slotsecs);
        // If we have a provider, search.
		
		/*echo "slottime:".$slotstime."\n";
		echo "slotsecs:".$slotsecs."\n";
		echo "slotbase:".$slotbase."\n";
		echo "evslots:".$evslots."\n";
		echo "slotsperday:".$slotsperday."\n";
		die("slots info");*/
		
		$query2 = " SELECT  u.id, u.fname, u.lname, lo.title, u.username, f.name as name, f.id as fid FROM users u, list_options lo, facility f WHERE  lo.seq = '" . $formdata['Specialty']."' AND u.speciality = lo.seq AND lo.list_id = 'especialidades' GROUP BY u.id";
		//die($query2);
		$res2 = sqlStatement($query2);
		
		if ( sqlNumRows($res2) > 0 ){
			//die(print_r(sqlFetchArray($res2)));
			while ( $row2 = sqlFetchArray($res2) ){
				$user = $sxe->addChild('User', '');
				$user->addAttribute('Name', $row2['fname']." ".$row2['lname']);
				$user->addAttribute('ID', $row2['id']);
				$user->addAttribute('Specialty', $row2['title']);
				$user->addAttribute('Username', $row2['username']);
				$user->addAttribute('Facility', $row2['name']);
				$user->addAttribute('Facilityid', $row2['fid']);
				
				//print_r($row2);
				//die("info");
				
				$providerid = $row2['id'];
				// Create and initialize the slot array. Values are bit-mapped:
				//   bit 0 = in-office occurs here
				//   bit 1 = out-of-office occurs here
				//   bit 2 = reserved
				// So, values may range from 0 to 7.
				//
				
				$slots = array_pad(array(), $slotcount, 0);
				// Note there is no need to sort the query results.
				
				$query = "SELECT users.fname, users.lname, users.username, pc_aid, pc_eventDate, pc_endDate, pc_startTime, pc_duration, 
				pc_recurrtype, pc_recurrspec, pc_alldayevent, pc_catid, pc_prefcatid 
				FROM openemr_postcalendar_events, users 
				WHERE pc_aid = '$providerid' AND ( pc_eid != '$eid' or pc_eid is null) AND 
				((pc_endDate >= '$sdate' AND pc_eventDate < '$edate') OR 
				(pc_endDate = '0000-00-00' AND pc_eventDate >= '$sdate' AND pc_eventDate < '$edate')) 
				AND openemr_postcalendar_events.pc_aid = users.id";
				
				/*$query = "SELECT users.fname, users.lname, users.username, pc_aid, pc_eventDate, pc_endDate, pc_startTime, pc_duration, 
				pc_recurrtype, pc_recurrspec, pc_alldayevent, pc_catid, pc_prefcatid 
				FROM openemr_postcalendar_events, users 
				WHERE pc_aid = 84 AND ( pc_eid != '$eid' or pc_eid is null) AND 
				((pc_endDate >= '$sdate' AND pc_eventDate < '$edate') OR 
				(pc_endDate = '0000-00-00' AND pc_eventDate >= '$sdate' AND pc_eventDate < '$edate')) 
				AND openemr_postcalendar_events.pc_aid = users.id";*/
				
				//return array('Success' => $query);
				
				$res = sqlStatement($query);
					//die ($query);
					
				while ($row = sqlFetchArray($res)) {
					//die ($query);
					
					$thistime = strtotime($row['pc_eventDate'] . " 00:00:00");
					if ($row['pc_recurrtype']) {
						//die("recurr");
						preg_match('/"event_repeat_freq_type";s:1:"(\d)"/', $row['pc_recurrspec'], $matches);
						$repeattype = $matches[1];

						preg_match('/"event_repeat_freq";s:1:"(\d)"/', $row['pc_recurrspec'], $matches);
						$repeatfreq = $matches[1];
						if (! $repeatfreq) $repeatfreq = 1;

						// This gets an array of exception dates for the event.
						$exdates = array();
						if (preg_match('/"exdate";s:\d+:"([0-9,]*)"/', $row['pc_recurrspec'], $matches)) {
						  $exdates = explode(",", $matches[1]);
						}

						$endtime = strtotime($row['pc_endDate'] . " 00:00:00") + (24 * 60 * 60);
						if ($endtime > $slotetime) $endtime = $slotetime;

						$repeatix = 0;
						while ($thistime < $endtime) {
							$adate = getdate($thistime);
							$thisymd = sprintf('%04d%02d%02d', $adate['year'], $adate['mon'], $adate['mday']);
							// Skip the event if a repeat frequency > 1 was specified and this is
							// not the desired occurrence, or if this date is in the exception array.
							
							if (!$repeatix && !in_array($thisymd, $exdates)) {
								//doOneDay($row['pc_catid'], $thistime, $row['pc_startTime'],
								//$row['pc_duration'], $row['pc_prefcatid']);
								//return array('Success' => "doOneDay1");
								//global $slots,  $slotstime, $slotbase, $slotcount, $input_catid;
								//return array('Success' => "val: ".print_r($slots));
								$catid = $row['pc_catid'];
								$starttime = $row['pc_startTime'];
								$udate2 = strtotime($starttime, $thistime);
								$duration = $row['pc_duration'];
								$prefcatid  = $row['pc_prefcatid'];
								if ($udate2 < $slotstime) return;
								$i = (int) ($udate2 / $slotsecs) - $slotbase;
								$iend = (int) (($duration + $slotsecs - 1) / $slotsecs) + $i;
								if ($iend > $slotcount) $iend = $slotcount;
								if ($iend <= $i) $iend = $i + 1;
								
								for (; $i < $iend; ++$i) {
								if ($catid == 2) {        // in office
									// If a category ID was specified when this popup was invoked, then select
									// only IN events with a matching preferred category or with no preferred
									// category; other IN events are to be treated as OUT events.
									if ($input_catid) {
										if ($prefcatid == $input_catid || !$prefcatid)
											$slots[$i] |= 1;
										 else
											$slots[$i] |= 2;
									} else {
										$slots[$i] |= 1;	
									}
										//break; // ignore any positive duration for IN
									} else if ($catid == 3) { // out of office
										$slots[$i] |= 2;
										break; // ignore any positive duration for OUT
									} else { // all other events reserve time
										$slots[$i] |= 4;
									}
								}
								
		  
								
							}
							if (++$repeatix >= $repeatfreq) $repeatix = 0;

							if ($repeattype == 0)        { // daily
								$adate['mday'] += 1;
							} else if ($repeattype == 1) { // weekly
								$adate['mday'] += 7;
							} else if ($repeattype == 2) { // monthly
								$adate['mon'] += 1;
							} else if ($repeattype == 3) { // yearly
								$adate['year'] += 1;
							} else if ($repeattype == 4) { // work days
								if ($adate['wday'] == 5)      // if friday, skip to monday
									$adate['mday'] += 3;
								else if ($adate['wday'] == 6) // saturday should not happen
									$adate['mday'] += 2;
								else
									$adate['mday'] += 1;
							} else {
								die("Invalid repeat type '$repeattype'");
							}
							$thistime = mktime(0, 0, 0, $adate['mon'], $adate['mday'], $adate['year']);
						}
					} else {
						//$val = doOneDay($row['pc_catid'], $thistime, $row['pc_startTime'],
						//$row['pc_duration'], $row['pc_prefcatid']);
								//die("noPcreccur");
								$catid = $row['pc_catid'];
								$starttime = $row['pc_startTime'];
								$udate2 = strtotime($starttime, $thistime);
								$duration = $row['pc_duration'];
								$prefcatid  = $row['pc_prefcatid'];
								//print_r($row);
								//die("row");
								//return array('Success' => "val: ".$udate2);
								//if ($udate2 < $slotstime) return;
								
								$i = (int) ($udate2 / $slotsecs) - $slotbase;
								$iend = (int) (($duration + $slotsecs - 1) / $slotsecs) + $i;
								if ($iend > $slotcount) $iend = $slotcount;
								if ($iend <= $i) $iend = $i + 1;
								
								//die("slotcount=>".$slotcount."\n");
								//die("i=>".$i."\n");
								//die("udate2=>".$thistime."\n");
								//die("starttime=>".$starttime."\n");
								//die("iend=>".$i."\n");
								
								for (; $i < $iend; ++$i) {
									//echo "$i count: ";
									//echo "$i catid: ".$catid."\n";
								if ($catid == 2) {        // in office
									//echo "catid = 2\n";
									// If a category ID was specified when this popup was invoked, then select
									// only IN events with a matching preferred category or with no preferred
									// category; other IN events are to be treated as OUT events.
									if ($input_catid) {
										if ($prefcatid == $input_catid || !$prefcatid)
											$slots[$i] |= 1;
										 else
											$slots[$i] |= 2;
									} else {
										$slots[$i] |= 1;	
									}
									break; // ignore any positive duration for IN
									} else if ($catid == 3) { // out of office
										//echo "catid = 3\n";
										$slots[$i] |= 2;
										break; // ignore any positive duration for OUT
									} else { // all other events reserve time
										//echo "catid = $i\n";
										$slots[$i] |= 4;
										
									}
									$end = $i;
								}
								//die("si no hay ountes, mal");
						
					}
				}
				//die("111");
				
				//print_r($slots);
				//die("slots");
				// Mark all slots reserved where the provider is not in-office.
				// Actually we could do this in the display loop instead.
				$inoffice = false;
				
				//print_r($row2);
				//print_r($slots);
				//die("slots");
				
				for ($i = 0; $i < $slotcount; ++$i) {
					if (($i % $slotsperday) == 0) $inoffice = false;
					if ($slots[$i] & 1) $inoffice = true;
					if ($slots[$i] & 2) $inoffice = false;
					//if (! $inoffice) $slots[$i] |= 4;
				}
				
				


				
				$ckavail = true;
				$lastdate = "";
				$ampmFlag = "am"; // establish an AM-PM line break flag
				$success = "";
				$continuar = true;
				$counter = 0;
				for ($i = 0; $i < $slotcount; ++$i ) {
					if(  $continuar ){	
						$available = true;
						for ($j = $i; $j < $i + $evslots; ++$j) {
							if ($slots[$j] >= 4) $available = false;
							
							
						}
						if (!$available) continue; // skip reserved slots
							
							$utime = ($slotbase + $i) * $slotsecs;
						$thisdate = date("Y-m-d", $utime);
						if ($thisdate != $lastdate) { 
							// if a new day, start a new row
							if ($lastdate) {
								$success .= "</div>";
								$success .= "</td>\n";
								$success .= " </tr>\n";
							}
							$lastdate = $thisdate;
							$success .= " <tr class='oneresult'>\n";
							$success .= "  <td class='srDate'>" . date("l", $utime)."<br>".date("Y-m-d", $utime) . "</td>\n";
							$success .= "  <td class='srTimes'>";
							$success .= "<div id='am'>AM ";
							$ampmFlag = "am";  // reset the AMPM flag
							$appointment = $sxe->addChild("appointment","");
						}

						$ampm = date('a', $utime);
						if ($ampmFlag != $ampm) { $success .= "</div><div id='pm'>PM "; }
						$ampmFlag = $ampm;

						$atitle = date("h:i a", $utime);
						$adate = getdate($utime);
						$anchor = "<a  onclick='setappt2(" .
						$adate['mday'] . "," .

						$adate['mon'] . "," .
						$adate['year'] . "," .

						$adate['hours'] . "," .
						$adate['minutes'] . ");'".
						" title='$atitle' alt='$atitle' href='#' " .
						">";
						$success .= (strlen(date('g',$utime)) < 2 ? "<span style='visibility:hidden'>0</span>" : "") .
						$anchor . date("g:i", $utime) . "</a> ";
						
						$appointment->addChild("date", $adate['year']."-".$adate['mon']."-".$adate['mday']);
							//$appointment->addChild("hour",$adate['hours'].":".$adate['minutes']." ".$adate);
							$appointment->addChild("hour",$atitle);
							$counter = $counter +1;

						// If the duration is more than 1 slot, increment $i appropriately.
						// This is to avoid reporting available times on undesirable boundaries.
						$i += $evslots - 1;
						if($counter == 10){
							$continuar = false;
						}
						//die ("slotcount: ".$slotcount." evslot: ".$evslots." slots[j]: ".$slots[$j]. " slotbase: ".$slotbase." slotsecs: ".$slotsecs);
					}
				}
					
				
				
				//return array('Success' => "110:0123");
			}
		}
		return array('Success' => $sxe->asXML());
	}
}
?>